package cp3120.model;

import java.util.LinkedList;
import java.util.List;

/**
 * A role is a collection of Permissions.
 *
 * Thread safe as long as nothing is using permissions externally.
 *
 * @author Adam Scarr <scarr.adam@gmail.com>
 */
public class Role {
    private List<Permission> permissions = new LinkedList<Permission>();
    private int id;
    private String name;

    public Role(int id, String name, List<Permission> permissions) {
        this.id = id;
        this.name = name;
        this.permissions = permissions;
    }

    public Role() {
    }

    public synchronized boolean hasPermission(String permissionName) {
        for (Permission p: permissions) {
            if (p.getName().equals(permissionName)) {
                return true;
            }
        }

        return false;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public synchronized List<Permission> getPermissions() {
        return permissions;
    }

    public synchronized void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }

    public int hashCode() {
        return id;
    }

    public boolean equals(Object other) {
        if (!(other instanceof Role)) {
            return false;
        }
        Role that = (Role)other;

        return this.id == that.id;
    }

    public String toString() {
        return name;
    }

    public Role clone() {
        Role clone = new Role();

        clone.id = this.id;
        clone.name = this.name;
        clone.permissions = new LinkedList<Permission>(this.permissions);

        return clone;
    }
}
